package org.alex.sample.web;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alex.sample.model.ExamUserRole;
import org.alex.sample.model.User;
import org.alex.sample.service.LoginService;
import org.alex.sample.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
	
	@Autowired
	private LoginService loginService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toLogin(HttpServletRequest request, Model model) throws Exception {
		String userName = "";
		String password = "";
		Cookie[] cks = request.getCookies(); //获取所有cookie
		if(cks != null && cks.length > 0) {
			for(Cookie c : cks) { //遍历所有cookie
				if(c.getName().equals("userName")) { //找到name为userName的cookie
					userName = URLDecoder.decode(c.getValue(), "utf-8"); //进行解码
				}
				if(c.getName().equals("password")) { //找到name为password的cookie
					password = URLDecoder.decode(c.getValue(), "utf-8");//解码
				}
			}
		}
		//把用户名和密码传到前端
		model.addAttribute("userName", userName);
		model.addAttribute("password", password);
		return "login/login";
	}
	
	//跳到UserControoler的users方法
	@RequestMapping(value = "/loginToManagerAndTeacher")
	public String managerAndteacher() {
		return "redirect:/users";
	}
	
	//跳到StudentController的stdent方法
	@RequestMapping(value = "/loginToStudent")
	public String student() {
		return "redirect:/student";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(Model model, @RequestParam String userName, @RequestParam String password, 
			@RequestParam(required = false) String rememberPassword, HttpSession session, 
			HttpServletResponse response) throws Exception {
		List<User> userList = loginService.findUserByUserName(userName);
		if(userList.size() > 0) { //查到该用户
			User user = userList.get(0); //得到用户
			if(password != null) { //输入的密码不为空
				String encodePassword = MD5.getMD5Code(password); //MD5加密密码
				Date currentTime = null;
				Calendar currentTimecalendar = Calendar.getInstance(); //创建日历对象
				currentTimecalendar.setTime(new Date()); //初始化时间
				currentTimecalendar.add(Calendar.MINUTE, -5); //减5分钟
				currentTime = currentTimecalendar.getTime(); //得到现在时间减去5分钟的时间
				if(user.getLastLockTime().before(currentTime)) { //判断在不在锁定时间内
					//不在锁定时间内
					if(encodePassword.equals(user.getPassword())) {
						//登录成功时
						user.setLoginFailCount(0); //失败次数清0
						loginService.updateUserLoginFailCount(user); //更新数据库
						//判断是否记住密码
						if(rememberPassword != null && rememberPassword != "") {
							//记住密码,保存cookie并且进行编码，因为cookie不能存中文(密码是不加密的密码)
							Cookie ckUserName = new Cookie("userName", URLEncoder.encode(user.getUserName(), "utf-8"));
							Cookie ckPassword = new Cookie("password", URLEncoder.encode(password, "utf-8"));
							ckUserName.setMaxAge(Integer.MAX_VALUE); //设置cookie保存的时间，否则关闭浏览器就被清掉
							ckPassword.setMaxAge(Integer.MAX_VALUE);
							response.addCookie(ckUserName);
							response.addCookie(ckPassword);
						}
						
						session.setAttribute("loginUser", user); //把查到的用户保存到session，设置权限菜单显示时需要用到
						Integer roleId = 0; //获取权限ID
						for(ExamUserRole examUserRole : user.getExamUserRole()) {
							if(examUserRole.getExamRole().getRoleId() == 1) {
								roleId = 1;
							}else if(examUserRole.getExamRole().getRoleId() == 2){
								roleId = 2;
							}else{
								roleId = 3;
							}
						}
						if(roleId == 1) { //id为1时跳转到学生方法
							return "redirect:/loginToStudent";
						}else {//id为2或3时跳转到教师和管理员方法
							return "redirect:/loginToManagerAndTeacher";
						}
					}else {
						//在锁定时间内
						user.setLoginFailCount(user.getLoginFailCount() + 1); //失败次数加1
						if(user.getLoginFailCount() == 3) { //失败3次时
							user.setLoginFailCount(0); //清0
							user.setLastLockTime(new Date()); //更新锁定时间
							loginService.updateUserLastLockTime(user); //更新数据库锁定时间
							model.addAttribute("fail", "密码错误3次，账号被锁定5分钟"); //失败3次锁定提示
							return "login/login"; //返回登录页面
						}
						loginService.updateUserLoginFailCount(user); //失败小于3次时更新数据库
						model.addAttribute("fail", "密码错误" + user.getLoginFailCount() + "/3次"); //失败小于3次的提示
						return "login/login"; //返回登录页面
					}
				}else {
					model.addAttribute("fail", "目前账号被锁定，无法登录，请稍等5分钟"); //在锁定时间内登录时的提示
					return "login/login"; //返回登录页面
				}
			}else {
				model.addAttribute("fail", "用户名或密码错误"); //密码为空时的提示
				return "login/login"; //返回登录页面
			}
		}else {
			model.addAttribute("fail", "用户名或密码错误"); //输入的用户名不存在时提示
			return "login/login"; //返回登录页面
		}
		
	}
	
}
